package sau.diyizu.media.video;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import sau.diyizu.media.ItemListener;
import sau.diyizu.media.R;
import sau.diyizu.media.bean.Video;

import java.util.List;

/**
 @author JYD
 @version 1.0
 @since 2020/12/15 19:29 */
public class VideoAdapter extends RecyclerView.Adapter<VideoAdapter.VH> {
    private List<Video> videoList;
    private LayoutInflater layoutInflater;
    private ItemListener listener = ItemListener.DEFAULT_NULL_INSTANCE;

    @Override
    public void onAttachedToRecyclerView(@NonNull RecyclerView recyclerView) {
        super.onAttachedToRecyclerView(recyclerView);
        layoutInflater = LayoutInflater.from(recyclerView.getContext());
    }

    /**
     设置数据 并发出更新数据的通知

     @param videoList 源数据
     */
    public void setDataAndNotify(@NonNull List<Video> videoList) {
        this.videoList = videoList;
        notifyDataSetChanged();
    }

    public List<Video> getVideoList() { return videoList; }

    @NonNull
    @Override
    public VH onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        VH vh = new VH(layoutInflater.inflate(R.layout.item_video, parent, false));
        vh.itemView.setOnClickListener(v -> listener.onTrigger(vh));
        return vh;
    }

    @Override
    public void onBindViewHolder(@NonNull VH vh, int position) {
        Video video = videoList.get(position);
        Glide.with(vh.itemView)
                .load(video.path)
                .placeholder(R.drawable.ic_video)
                .into(vh.thumbnail_iv);
        vh.content_tv.setText(video.name);
    }

    @Override
    public int getItemCount() { return videoList != null ? videoList.size() : 0; }

    public void setItemListener(ItemListener listener) {
        this.listener = listener;
    }

    static class VH extends RecyclerView.ViewHolder {
        ImageView thumbnail_iv;
        TextView content_tv;

        public VH(@NonNull View itemView) {
            super(itemView);
            thumbnail_iv = itemView.findViewById(R.id.thumbnail_iv);
            content_tv = itemView.findViewById(R.id.content_tv);
        }
    }
}
